package com.zsc.edu.gateway.modules.iot.tsl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsc.edu.gateway.modules.iot.tsl.dto.ParamDto;
import com.zsc.edu.gateway.modules.iot.tsl.entity.CompareParam;
import com.zsc.edu.gateway.modules.iot.tsl.entity.Param;
import com.zsc.edu.gateway.modules.iot.tsl.mapper.CompareParamMapper;
import com.zsc.edu.gateway.modules.iot.tsl.mapper.ParamMapper;
import com.zsc.edu.gateway.modules.iot.tsl.repo.CompareParamRepository;
import com.zsc.edu.gateway.modules.iot.tsl.repo.ParamRepository;
import com.zsc.edu.gateway.modules.iot.tsl.service.ParamService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author zhuang
 */
@AllArgsConstructor
@Service
public class ParamServiceImpl extends ServiceImpl<ParamRepository, Param> implements ParamService {
    private final ParamMapper mapper;
    private final ParamMapper paramMapper;
    private final CompareParamMapper compareParamMapper;
    private final CompareParamRepository compareParamRepository;
    @Override
    @Transactional
    public Boolean create(List<ParamDto> params, Long id, Param.ForeignType foreignType) {
        List<Param> paramsToInsert = params.stream()
                .map(dto -> {
                    Param param = mapper.toEntity(dto);
                    param.setForeignId(id);
                    param.setForeignType(foreignType);
                    return param;
                })
                .collect(Collectors.toList());
        baseMapper.insert(paramsToInsert);
        return true;
    }


    @Override
    @Transactional
    public Boolean update(List<ParamDto> paramDto, Long id) {
        List<Param> params = baseMapper.selectList(new LambdaQueryWrapper<Param>()
                .eq(Objects.nonNull(id), Param::getForeignId, id));
        if (!params.isEmpty() && !paramDto.isEmpty()) {
            List<Param> updatedParams = IntStream.range(0, Math.min(params.size(), paramDto.size()))
                    .parallel()
                    .mapToObj(i -> {
                        Param param = params.get(i);
                        ParamDto dto = paramDto.get(i);
                        paramMapper.convert(dto, param);
                        return param;
                    })
                    .collect(Collectors.toList());
            baseMapper.updateById(updatedParams);
        }
        return true;
    }

    @Override
    @Transactional
    public Boolean delete(Long id) {
        return baseMapper.delete(new LambdaQueryWrapper<Param>()
                .eq(Objects.nonNull(id), Param::getForeignId, id)) > 0;
    }

}
